package com.example.networkprofiler;
import java.net.*;
import java.security.SecureRandom;
import java.io.*;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import android.net.TrafficStats;


public class SpeedTestThreadHttp implements Runnable {
	private final String USER_AGENT = "Mozilla/5.0";
	 
	 static AtomicInteger count = null;
	 static long startTime = 0;
	 static long startData = 0;
	 static long endTime = 0;
	 static long endData = 0;
	 String url = "http://www.cs.purdue.edu/homes/jin72/";
	 private HttpURLConnection con;
	 String inputLine;
		StringBuffer response;
		private BufferedReader in;
	public SpeedTestThreadHttp(int i){
		
		if(count == null) count = new AtomicInteger(1);
		else {			
			count.getAndAdd(1);
		}
		try{
			url += i + ".txt";
			URL obj = new URL(url);
			con = (HttpURLConnection) obj.openConnection();
			
			
			// optional default is GET
			con.setRequestMethod("GET");
	 
			//add request header
			con.setRequestProperty("User-Agent", USER_AGENT);
			int responseCode = con.getResponseCode();
	 
			if(InetAddress.getByName("www.cs.purdue.edu").isReachable(1000) == false){
				System.err.println("Unreachable address");
			}
			System.gc();
			
			response = new StringBuffer();
		
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	public void run(){
		
		
		try{	
			startTiming();
			in = new BufferedReader(new InputStreamReader(con.getInputStream()));		 
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			
			endTiming();
			in.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		con.disconnect();
	
	}
	
	public synchronized void startTiming(){
		if(count.getAndDecrement() ==1) {
			startData = TrafficStats.getTotalRxBytes();
			startTime=System.currentTimeMillis();
			System.out.println(startData+ " "+startTime);
		}else{
			System.gc();
		}
	}
	
	public synchronized void endTiming(){
		if(count.getAndIncrement() ==0){			
			endTime = System.currentTimeMillis(); 
			endData = TrafficStats.getTotalRxBytes();
			System.out.println(endData+ " "+endTime);
		}
	}
	

}
